<template>
  <a-modal :visible="visible"  width="1200px" title="商品详情" :footer="null" @cancel="cancel">
    <div class="detailModelCss">
      <a-card
        style="width:100%"
        :tab-list="tabList"
        :active-tab-key="key"
        @tabChange="key => onTabChange(key, 'key')"
      >
        <div v-show="tabIndex==1">
          <a-form-model
              ref="ruleForm"
              :model="form"
              :rules="rules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
            <a-form-model-item label="商品名称" ref="name" prop="name">
              <a-input v-model="form.name" @blur="() => {$refs.name.onFieldBlur();}" placeholder="请填写商品名称"/>
            </a-form-model-item>
            <a-form-model-item label="商品分类" ref="category_id" prop="category_id" v-if="visible" placeholder="请选择">
              <a-cascader v-model="form.category_id" :options="categoryList" placeholder="请选择商品分类"
              @change="onChangeCategory"
              />
            </a-form-model-item>
            <a-form-model-item label="供应链" ref="type" prop="type" placeholder="请选择">
              <a-select v-model="form.type" @change="typeChange" placeholder="请选择">
                <a-select-option v-for="(item,index) in typeList" :key="index" :value="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="供应商" ref="supplier_id" prop="supplier_id" placeholder="请选择">
              <a-select v-model="form.supplier_id" @change="supplierChange" placeholder="请选择">
                <a-select-option v-for="(item,index) in supplierList" :key="index" :value="item.id">{{item.contacts}}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="取货方式" ref="is_type" prop="is_type" placeholder="请选择">
              <a-radio-group v-model="form.is_type" @blur="() => {$refs.is_type.onFieldBlur();}">
                <a-radio :value="1">
                  快递
                </a-radio>
                <a-radio :value="2">
                  到店
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-item label="商品图片">
              <a-upload
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :action="$api.upload"
                :before-upload="beforeUpload"
                @change="handleGoodsChange"
              >
                <img v-if="imageUrl4Goods" :src="imageUrl4Goods" alt="avatar" />
                <div v-else>
                  <a-icon :type="loadings ? 'loadings' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-model-item label="是否可退单" ref="is_refund" prop="is_refund">
              <a-radio-group v-model="form.is_refund" @blur="() => {$refs.is_refund.onFieldBlur();}">
                <a-radio :value="1">
                  是
                </a-radio>
                <a-radio :value="2">
                  否
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="退单手续费" v-if="form.is_refund==1" ref="refund_fee" prop="refund_fee">
              <a-input suffix="%" v-model="form.refund_fee" @blur="() => {$refs.refund_fee.onFieldBlur();}" placeholder="请填写退单手续费"/>
            </a-form-model-item>
            <a-form-model-item label="上架时间">
              <a-range-picker
                :default-value="[moment(form.slaunch_time || new Date(), dateFormat), moment(form.dlaunch_time|| new Date(), dateFormat)]"
                :ranges="{ Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] }"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                @change="onChangeUpTime"
              />
            </a-form-model-item>
            <a-form-model-item label="有效时间">
              <a-range-picker
                :default-value="[moment(form.starttime|| new Date(), dateFormat), moment(form.endtime|| new Date(), dateFormat)]"
                :ranges="{ Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] }"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                @change="onChangeInValidTime"
              />
            </a-form-model-item>
            <a-form-model-item label="抢购时间">
              <a-range-picker
                :default-value="[moment(form.srush_time|| new Date(), dateFormat), moment(form.drush_time|| new Date(), dateFormat)]"
                :ranges="{ Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] }"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                @change="onChangeqBuyTime"
              />
            </a-form-model-item>
            
            <a-form-item
              label="给业务员的佣金比例"
              ref="commission" prop="commission"
              >
              <a-input
                :maxLength="6"
                suffix="%"
                v-model="form.commission"
                @blur="() => {$refs.commission.onFieldBlur();}"
                placeholder="请输入业务员的佣金比例"/>
            </a-form-item>
            
            <a-form-model-item label="自动确认收货" ref="receivetime" prop="receivetime" extra="填写0时,代表下单完成后马上收货核销">
              <a-input v-model="form.receivetime" suffix="天" @blur="() => {$refs.receivetime.onFieldBlur();}" placeholder="请填写自动确认收货时间"/>
            </a-form-model-item>
            <a-form-model-item label="对谁可见" ref="is_status" prop="is_status">
              <a-select v-model="form.is_status" placeholder="请选择">
                <a-select-option :value="-1">全部</a-select-option>
                <a-select-option :value="1">分销商</a-select-option>
                <a-select-option :value="2">渠道商</a-select-option>
                <a-select-option :value="3">批发商</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="是否需要身份证" ref="is_need_idcard" prop="is_need_idcard">
              <a-radio-group v-model="form.is_need_idcard" @blur="() => {$refs.is_need_idcard.onFieldBlur();}">
                <a-radio :value="1">
                  是
                </a-radio>
                <a-radio :value="2">
                  否
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="是否需要预约" ref="is_need_appointment" prop="is_need_appointment">
              <a-radio-group v-model="form.is_need_appointment" @blur="() => {$refs.is_need_appointment.onFieldBlur();}">
                <a-radio :value="1">
                  是
                </a-radio>
                <a-radio :value="2">
                  否
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            
            <a-form-model-item label="排序" ref="sort" prop="sort">
              <a-input v-model="form.sort" @blur="() => {$refs.sort.onFieldBlur();}" placeholder="数值越大排序越靠前"/>
            </a-form-model-item>
            
            <a-form-model-item label="上传海报">
              <a-upload
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :action="$api.upload"
                :before-upload="beforeUpload"
                @change="handleHaibaoChange"
              >
                <img v-if="imageUrl4haibao" :src="imageUrl4haibao" alt="avatar" />
                <div v-else>
                  <a-icon :type="loadings ? 'loadings' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-model-item>
            <a-form-model-item label="海报文案" ref="copywriting" prop="copywriting">
              <a-input type="textarea" v-model="form.copywriting" @blur="() => {$refs.copywriting.onFieldBlur();}" placeholder="请填写海报文案"/>
            </a-form-model-item>
            <a-form-model-item label="备注" ref="remark" prop="remark">
              <a-input v-model="form.remark" @blur="() => {$refs.remark.onFieldBlur();}" placeholder="请填写备注"/>
            </a-form-model-item>
          </a-form-model>
        </div>
        <div v-show="tabIndex==2">
          <a-form-item label="商品详情">
            <!-- :value="form.detailed || detailed" -->
            <editor
              style="min-height: 300px;"
              :value="form.detailed || detailed"
              @getEditorText="getEditorText"
            ></editor>
          </a-form-item>
        </div>
        <div v-if="tabIndex==3">
          <create-sku :spectList="spectList"></create-sku>
        </div>
      </a-card>
      <div class="margT10 modelBottonBtnBox">
        <a-button type="primary" @click="saveAll" :loading="submitLoading">提交</a-button>
        <a-button class="margL10" type="primary" @click="cancel">取消</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import moment from 'moment';
// 引入角色列表
import { getRoLeList } from '../../../../api/system'
import Editor from '@/components/Editor/QuillEditor.vue';
import CreateSku from './CreateSku';

import { mapGetters,mapActions } from 'vuex'

// 表单字段
// const fields = ['id', 'username','name', 'sex', 'role_id', 'department_id', 'mobile', 'campus_id', 'volunteer', 'teacher', 'remark', 'introduction']
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
var numReg = /^[0-9]+$/;
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    supplierList: {
      type: Array,
      default: () => null
    },
  },
  components:{
    CreateSku,
    Editor
  },
  data () {
    let checkValidDay = (rule, value, callback) => {
      console.log('Number.isInteger(value)',numReg.test(value))
      if (value.trim() === '') {
        callback(new Error('请填写有效期'));
      } else if (!numReg.test(value)) {
        callback(new Error('请填写为数字的有效期'));
      } else {
        callback();
      }
    };
    return {
      submitLoading:false,
      // 对谁可见
      indeterminate: true,
      checkAll: false,
      typeList:[],
      plainOptions:['分销商','渠道商','批发商'],
      key:'1',
      tabList: [
        {
          key: '1',
          tab: '基本',
        },
        {
          key: '2',
          tab: '详情',
        },
        {
          key: '3',
          tab: '规格',
        },
      ],
      // 商品分类
      category_options:[],
      loadings: false,
      imageUrl4Goods:'',
      imageUrl4haibao:'',
      rules: {
        supplier_id:[
          { required: true, message: '请选择供应商', trigger: 'change' },
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在1~50个之间', trigger: 'blur' },
        ],
        category_id:[
          { required: true, message: '请选产品分类', trigger: 'change' },
        ],
        is_type:[
          { required: true, message: '请选择取货方式', trigger: 'change' },
        ],
        is_refund:[
          { required: true, message: '请选择是否可退单', trigger: 'change' },
        ],
        is_need_idcard:[
          { required: true, message: '下单是否需要身份证', trigger: 'change' },
        ],
        is_need_appointment:[
          { required: true, message: '下单是否需预约', trigger: 'change' },
        ],
        commission:[
          { required: true, message: '请输入业务员的佣金比例', trigger: 'blur' },
          { pattern:this.$reg.float, message: '请输入数字'}
        ],
        is_status:[
          { required: true, message: '请选择对谁可见', trigger: 'change' },
        ],
        receivetime:[{ required: true, message: '请输入自动确认收货天数', trigger: 'blur' },
        {
          pattern:this.$reg.digit,
          message: '请输入整数',
        },],
        refund_fee:[{ required: true, message: '请输入退单手续费', trigger: 'blur' },
        {
          pattern:this.$reg.float,
          message: '请输入数字',
        },],
        valid: [{ validator: checkValidDay, trigger: 'blur' }],
        sort:[
        {
          pattern:this.$reg.digit,
          message: '请输入整数',
        },],
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form:{
        detailed:'详情'
      },
      detailed:'详情',
      detail:'详情',
      tabIndex: 1,
      key:1,
      dateFormat: 'yyyy/MM/DD HH:mm:ss'
    }
  },
  watch:{
    model:{
      handler(newValue) {
        console.log('---new model----',newValue)
        this.detailed = this.model.detailed
      },
      immediate: true,
      deep: true
    },
    visible:{
      handler(newValue) {
        console.log('handler_model',this.model)
        this.submitLoading = false
        if(newValue){
          this.tabIndex = 1
          this.key = '1'
          if(this.model&&this.model.id>0){
            this.form = this.model
            this.form.detailed = this.model.detailed
            console.log("detail",this.form.detailed)
            // this.form.type = val
            this.imageUrl4Goods = this.model.image
            this.imageUrl4haibao = this.model.imgs
            this.SET_PROUDCT_ID(this.model.id)
            this.getSpecsPage(this.model.id)
            this.$forceUpdate()
            console.log('getSpecsPage__END')
          }else{
            this.form = {}
            this.form.starttime = new Date()
            this.form.endtime = new Date()
            this.form.slaunch_time = new Date()
            this.form.dlaunch_time = new Date()
            this.form.srush_time = new Date()
            this.form.drush_time = new Date()
          }
          this.typeList = this.$myUtils.getTypeList
          this.form.type = this.goods_type
          console.log("this.form.type",this.form.type)
          this.GET_CATEGORY_LIST({})
          this.$forceUpdate()
        }
      },
      immediate: true,
      deep: true
    }
  },
  beforeDestroy() {
    this.bus.$off('getSpecsPage')
  },
  mounted () {
    this.bus.$on('getSpecsPage',()=>{
      this.getSpecsPage(this.model.id)
    })
    // 当 model 发生改变时，为表单设置值
    // this.$watch('model', () => {
    //   if (this.model && this.model.id>0) {
    //     //刚进来的时候需要在vuex中存proudct_id
    //     this.SET_PROUDCT_ID(this.model.id)
    //   } else {
    //     this.form = {
          
    //     }
    //   }
    //   // this.model && this.form.setFieldsValue(pick(this.model, fields))
    // })
  },
  computed:{
      ...mapGetters(['goods_type','goods_detail_tab_index','spectList','categoryList']),
  },
  methods: {
    moment,
    ...mapActions(['SET_GOODS_TYPE','SET_PROUDCT_ID','SET_SPECTLIST','GET_CATEGORY_LIST']),
    //修改供应商
    supplierChange(val) {
      this.form.supplier_id = val
    },
    typeChange(val) {
      this.form.type = val
      this.$forceUpdate()
      // this.SET_GOODS_TYPE(val)
    },
    onChange(checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length;
      this.checkAll = checkedList.length === this.plainOptions.length;
    },
    onCheckAllChange(e) {
      this.form.is_status = e.target.checked ? ['分销商','渠道商','批发商'] : [],
      this.indeterminate = false,
      this.checkAll = e.target.checked,
      this.$forceUpdate()
    },
    getSpecsPage(proudct_id) {
      const params = {
        pageNo:1,
        pageSize:1000,
        proudct_id
      }
      this.$productApi.SpecsPage(params).then(res=>{
        if(res.ret == 200) {
          // this.spectList = res.data.data
          console.log("set_spectList",res.data.data)
          this.SET_SPECTLIST(res.data.data)
          // this.$forceUpdate()
        }
      })
    },
    displayRender({ labels }) {
      return labels[labels.length - 1];
    },
    // getCategoryRecursion() {
    //   const params = {
    //   }
    //   this.$productApi.CategoryRecursion(params).then(res => {
    //     if( res.ret == 200 ) {
    //       this.CategoryData = res.data == '未查询到数据'?[]:res.data
    //     }
    //   })
    // },
    onChangeCategory(value,selectedOptions) {
      // console.log(value,selectedOptions);
    },
    // 富文本编辑器内容变更
    getEditorText (html) {
      // console.log(html)
      this.form.detailed = html
      // this.$emit('getAllContent', html)
    },
    //抢购时间改变
    onChangeqBuyTime(val) {
      const format = this.dateFormat
      const srart_time = val[0]._d
      const end_time = val[1]._d
      //开始抢购时间
      this.form.srush_time = moment(srart_time).format(format)
      //结束抢购时间
      this.form.drush_time = moment(end_time).format(format)
    },
    //上下架时间改变
    onChangeUpTime(val) {
      const format = this.dateFormat
      const srart_time = val[0]._d
      const end_time = val[1]._d
      //开始上架时间
      this.form.slaunch_time = moment(srart_time).format(format)
      //结束上架时间
      this.form.dlaunch_time = moment(end_time).format(format)
    },
    //过期/有效时间改变
    onChangeInValidTime(val) {
      const format = this.dateFormat
      const srart_time = val[0]._d
      const end_time = val[1]._d
      const st = moment(srart_time).format(format)
      //有效时间从****开始
      this.form.starttime = moment(srart_time).format(format)
      //拿到到期时间
      this.form.endtime = moment(end_time).format(format)
      //计算出有效期(天)
      this.form.valid = (new Date(this.form.endtime).getTime() - new Date(st).getTime())/1000/60/60/24
      console.log("this.form.valid",this.form.valid)
    },
    // 商品图片的改变时间
    handleGoodsChange(info) {
      if (info.file.status === 'uploading') {
        this.loadings = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl4Goods = info.file.response.data.url;
          this.loadings = false;
          // this.$emit('getImage', info.file.response.data.url)
        });
      }
    },
    handleHaibaoChange(info) {
      console.log('------------info----------', info)
      if (info.file.status === 'uploading') {
        this.loadings = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          console.log('--------------logo---------------', info.file.response.data.url)
          this.imageUrl4haibao = info.file.response.data.url;
          this.loadings = false;
          // this.$emit('getImage', info.file.response.data.url)
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('请上传JPG/PNG格式的图片!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('所上传的图片请在2MB之内!');
      }
      return isJpgOrPng && isLt2M;
    },
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // alert('submit!');
          console.log("valid",valid)
        } else {
          this.$message.error('存在必要字段尚未填写!!');
          return false;
        }
      });
    },
    onTabChange(key, type) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          
          console.log('onTabChange valid!');
          this.tabIndex = key
          this.key = key
          console.log('key:',key);
          if(key==2){
            if(this.model&&this.model.id){
              this.form.detailed = this.model.detailed
              console.log('key==2:form.detailed',this.form.detailed)
              this.$forceUpdate()
            }
          }
          if(key==3){
            if(this.model&&this.model.id){
              this.getSpecsPage(this.model.id)
            }else{
              this.saveAllFirst()
            }
          }
        } else {
          this.$message.error('存在必要字段尚未填写!!');
          return false;
        }
      });
    },
    //切换到规格的时候预先保存
    saveAllFirst() {
      this.form.type = this.goods_type
      console.log("this.goods_type",this.goods_type)
      this.form.image = this.imageUrl4Goods
      this.form.imgs = this.imageUrl4haibao
      this.form.sort = Number(this.form.sort)
      console.log('form',this.form)
      this.$productApi.ProductSave(this.form).then(res=>{
        if(res.ret==200){
          const proudct_id = Number(res.data.id)
          //第一次保存的时候需要在vuex中存proudct_id
          this.SET_PROUDCT_ID(proudct_id)
          console.log("ProductSave__proudct_id",proudct_id)
          this.form.id = proudct_id
          this.getSpecsPage(proudct_id)
        }
      })
    },
    saveAll() {
      this.submitLoading = true
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if(!this.imageUrl4Goods){
            this.$message.error('无法提交，原因：商品图片尚未设置');
            this.submitLoading = false
            return
          }
          console.log("this.spectList",this.spectList)
          //判断是否设置了商品规格
          if(this.spectList.length<=0){
            this.$message.error('无法提交，原因：商品规格尚未设置');
            this.submitLoading = false
            return
          }
          this.form.type = this.goods_type
          this.form.image = this.imageUrl4Goods
          this.form.imgs = this.imageUrl4haibao
          this.form.sort = Number(this.form.sort)
          this.$productApi.ProductSave(this.form).then(res=>{
            if(res.ret == 200) {
              this.$message.success('操作成功!');
              this.$emit('cancel')
              this.submitLoading = false
            }
          }).finally(res=>{
            this.submitLoading = false
          })
        } else {
          this.$message.error('存在必要字段尚未填写!!');
          this.submitLoading = false
          return false;
        }
      });
      
    },
    cancel() {
      this.$emit('cancel')
      this.form = {
        category_id:[],
        // is_status:[]
      }
      // this.$refs.ruleForm.resetFields();
    },
  }
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.avatar-uploader img {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>

